package edu.ensmp.ckEditor.gui;

import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;

import edu.ensmp.ckEditor.main.Launcher;
import edu.ensmp.ckEditor.util.UiConstants;


public class Genius implements ActionListener {

	JFrame geniusFrame = new JFrame();
	JButton suggestButton = new JButton("Hint");
	JTextArea textField = new JTextArea();

	public Genius() {

		geniusFrame.setSize(200, 600);

		final Point editorFrameLocation = Launcher.getEditorGUI()
				.getEditorFrame().getLocation();

		geniusFrame.setLocation(editorFrameLocation.x
				+ UiConstants.WINDOW_WIDTH, editorFrameLocation.y);

		textField.setSize(100, 600);
		textField.setEditable(false);

		// System.out.println(finalResult);
		// textField.setText(finalResult);

		geniusFrame.setLayout(new BorderLayout());
		geniusFrame.add(suggestButton, BorderLayout.NORTH);
		geniusFrame.add(textField, BorderLayout.CENTER);

		suggestButton.addActionListener(this);

		geniusFrame.setVisible(true);
	}

	public String getGoogleSuggestion(String keyword) {

		String inputLine;
		String result = "No Result";
		try {

			final URL googleSuggestURL = new URL(
					"http://www.google.com/complete/search?hl=en&js=true&qu="
							+ keyword);

			BufferedReader in = new BufferedReader(new InputStreamReader(
					googleSuggestURL.openStream()));

			while ((inputLine = in.readLine()) != null) {
				result = inputLine;
			}
			in.close();
		} catch (Exception e) {
			result = "Nothing";
			e.printStackTrace();
		}

		return result;

	}

	public String parseGoogleSuggestion(String unparsedGS) {
		String[] stringArray = unparsedGS.split("\"");
		String result = "Suggestions:";

		for (int x = 3; x < stringArray.length; x = x + 6) {
			System.out.println(stringArray[x]);
			result = result.concat("\n" + stringArray[x]);
		}
		return result;
	}

	public void actionPerformed(ActionEvent event) {
		String keyword = Launcher.getEditorGUI().getPropositionTextField()
				.getText();
		textField.setText(parseGoogleSuggestion(getGoogleSuggestion(keyword)));
	}

}
